#!/bin/bash

OUTFILE=/workdir/$3
SCORE=0
CARGO=/workspace/.cargo/bin/cargo

git config --global user.email "compilers@software.nju.edu.cb"
git config --global user.name "tracer-compiler2023"

gitcode_dir=$(find . -maxdepth 1 -type d -name "gitcode_*" | head -n 1)
if [ -z "$gitcode_dir" ]; then
  echo "{\"score\":$SCORE, \"message\":\"Error: 未找到 gitcode_ 目录\"}" > $OUTFILE
  exit -1
fi
cd "$gitcode_dir"

git fetch
git checkout lab6
if [ $? -ne 0 ]; then
  echo "{\"score\":$SCORE, \"message\":\"Error: cannot checkout to branch lab6\"}" > $OUTFILE
  exit -1
fi

git reset --hard HEAD

$CARGO clean

# 编译 cargo，如果失败，把错误写入 OUTFILE
build_output=$($CARGO build --release --target x86_64-unknown-linux-gnu 2>&1)
if [ $? -ne 0 ]; then
  escaped_output=$(echo "$build_output" | sed ':a;N;$!ba;s/\n/\\n/g' | sed 's/"/\\"/g')
  echo "{\"score\":$SCORE, \"message\":\"Error: fail to build. $escaped_output\"}" > $OUTFILE
  exit -1
fi

# 运行 validate.py，捕获所有输出
timeout 300s python3 ../validate.py > $OUTFILE 2>&1
if [ $? -ne 0 ]; then
  # 如果 Python 报错，也把最后的 OUTFILE 内容保留，不覆盖
  echo "{\"score\":$SCORE, \"message\":\"Error: validate.py failed or timeout. See output for details.\"}" > $OUTFILE
  exit -1
fi
